<template>
  <div class="login-container">
    <el-form ref="ruleFormRef" style="max-width: 100%;margin-left: 10%;" :model="ruleForm" status-icon :rules="rules"
      label-width="auto" class="demo-ruleForm">
      <el-form-item label="请输入手机号" prop="phone">
        <el-input style="width: 250px;" v-model.number="ruleForm.phone" @keyup.enter="submitForm(ruleFormRef)" />
      </el-form-item>

      <el-form-item label="请输入密码" prop="pwd">
        <el-input style="width: 250px;" v-model="ruleForm.pwd" type="password" autocomplete="off"
          @keyup.enter="submitForm(ruleFormRef)" /> <!-- 在这里添加事件监听器 -->
      </el-form-item>


      <el-form-item>
        <el-button style="display: inline-block;margin-left: 20%;margin-top: 10px;" type="primary"
          @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button style="display: inline-block;margin-top: 10px;" @click="router.push('/register')">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
  
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus';
import { loginApi } from '@/api/api';
import router from '@/router';


//声明表单对象名称，关联整个表单中的元素
const ruleFormRef = ref<FormInstance>()
//手机号校验
const checkPhone = (rules: any, value: any, callback: any) => {
  rules
  if (!value) {
    return callback(new Error('手机号不能为空'))
  }
  callback()

}
//密码校验
const checkpwd = (rules: any, value: any, callback: any) => {
  rules
  if (!value) {
    return callback(new Error('密码不能为空'))
  }
  callback(); // 校验通过
}

// 表单的数据
const ruleForm = reactive({
  phone: '13333333333',
  pwd: '123456',
})
//校验规则数组
const rules = reactive<FormRules<typeof ruleForm>>({
  pwd: [{ validator: checkpwd, trigger: 'blur' }],
  phone: [{ validator: checkPhone, trigger: 'blur' }],
})

// 声明一个登录函数（增加完整的处理逻辑：请求、响应、异常）
// axios请求需要通过异步方式声明：async/await
async function handleLogin() {
  try {
    const response = await loginApi(ruleForm);
    console.log('登录响应数据', response);
    if (response.code === 200) {
      ElMessage.success('登录成功');
      //储存数据到本地       使用sessionStorage，关闭浏览器后数据清除    使用localStorage，数据永久保存（关闭浏览器不会清除），只有手动清除
      localStorage.setItem('name', response.data.manager.managerName);  //右上角显示
      localStorage.setItem('phone', response.data.manager.managerPhone);
      localStorage.setItem('token', response.data.token);  //获取token（登录验证、安全校验）
      localStorage.setItem('id', response.data.manager.managerId);  //获取菜单列表(这个toString就只是为了不报错)

      localStorage.setItem('permissionList', JSON.stringify(response.data.permissions));  //获取API列表(这个JSON.stringify是为了存储到本地)
      localStorage.setItem('buttonList', JSON.stringify(response.data.buttons));  //获取按钮列表(这个JSON.stringify是为了存储到本地)
      localStorage.setItem('menuList', JSON.stringify(response.data.menus));  //获取菜单列表(这个JSON.stringify是为了存储到本地)


      //跳转到首页
      // setTimeout(() => {
      router.push('/index')
      // }, 200);
      //清空表单数据
      ruleForm.phone = '';
      ruleForm.pwd = '';
    } else {
      ElMessage.error(response.msg);
    }
  } catch (error) {
    ElMessage.error('操作失败，请稍后再试');
  }
}

//提交数据
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      //如果验证通过，这调用登录方法
      handleLogin()
    } else {
      ElMessage({
        message: '数据格式有误',
        type: 'error',
        duration: 1000, // 消息提示框显示的时间，单位是毫秒
      });
    }
  })
}


</script>

<style scoped>
.login-container {
  /* background-image: src('@/assets/3.jpg'); */
  border-radius: 10px;
  padding-top: 80px;
  padding-bottom: 30px;
  background-color: aqua;
  margin: 30px auto;
  width: 500px
}
</style>